package com.jt.moneybook.Fragments;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaDataSource;
import android.os.Bundle;
import android.service.quicksettings.Tile;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jt.moneybook.models.Cost;
import com.jt.moneybook.CostActivity;
import com.jt.moneybook.models.CostLab;
import com.jt.moneybook.R;
import com.jt.moneybook.utils.DateFormatConverter;

import java.util.Date;
import java.util.List;
import java.util.UUID;

public class CostListFragment extends Fragment {
    private static final String DIALOG_SEARCH = "DialogSearch";

    private static final int REQUEST_SEARCH = 0;

    private RecyclerView mCostRecyclerView;
    private CostAdapter mAdapter;

    private int mPosition;

    private FloatingActionButton mFab;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, 1, 0, "删除");

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                Cost cost = mAdapter.mCosts.get(mPosition);
                CostLab.get(getActivity()).deleteCost(cost);
                updateUI();
                break;

        }

        return super.onContextItemSelected(item);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cost_list, container, false);

        mFab = (FloatingActionButton) getActivity().findViewById(R.id.fab_add);
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPosition=mAdapter.mCosts.size();
                Cost cost = new Cost(UUID.randomUUID());
                CostLab.get(getActivity()).addCost(cost);
                Intent intent = CostActivity.newIntent(getActivity(), cost.getId());
                startActivity(intent);
            }
        });

        mCostRecyclerView = (RecyclerView) view.findViewById(R.id.cost_recycler_view);
        /*摆放列表项的任务被交给LayoutManager，其还负责定义屏幕滚动行为*/
        mCostRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mCostRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        mCostRecyclerView.setOnCreateContextMenuListener(
                new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                        contextMenu.add(0, 1, 0, "删除");
                    }
                }
        );

        updateUI();
        return view;
    }

    private void updateUI() {
        CostLab costLab = CostLab.get(getActivity());
        List<Cost> costs = costLab.getCosts();
        for (Cost cost : costs) {
            String title = cost.getTitle();
            if (title == null || title.equals("")) {
                CostLab.get(getActivity()).deleteCost(cost);
                costs.remove(cost);
            }
        }

        if (mAdapter == null) {
            mAdapter = new CostAdapter(costs);
            mCostRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.setCosts(costs);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void updateUI(Date date, int conditionCode) {
        CostLab costLab = CostLab.get(getActivity());
        List<Cost> costs = costLab.getCosts(date, conditionCode);
        if (mAdapter == null) {
            mAdapter = new CostAdapter(costs);
            mCostRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.setCosts(costs);
            mAdapter.notifyDataSetChanged();
        }
    }


    private class CostHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mTitleTextView;
        private TextView mMoneyTextView;
        private TextView mDateTextView;
        private Cost mCost;

        public CostHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_cost, parent, false));

            itemView.setOnClickListener(this);
            mTitleTextView = (TextView) itemView.findViewById(R.id.cost_title);
            mMoneyTextView = (TextView) itemView.findViewById(R.id.text_money);
            mDateTextView = (TextView) itemView.findViewById(R.id.cost_date);
        }

        public void bind(Cost cost) {
            mCost = cost;
            mTitleTextView.setText(mCost.getTitle());
            mMoneyTextView.setText(mCost.getMoney() + "元");
            if ("收入".equals(mCost.getDirection())) {
                mMoneyTextView.setTextColor(0xff2e8b57);
            }
            mDateTextView.setText(DateFormatConverter.convert(mCost.getDate()));
        }

        @Override
        public void onClick(View view) {
            Intent intent = CostActivity.newIntent(getActivity(), mCost.getId());
            mPosition = getAdapterPosition();
            startActivity(intent);
        }
    }


    private class CostAdapter extends RecyclerView.Adapter<CostHolder> {
        private List<Cost> mCosts;

        public CostAdapter(List<Cost> costs) {
            mCosts = costs;
        }

        @NonNull
        @Override
        public CostHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

            return new CostHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(@NonNull final CostHolder costHolder, int i) {
            Cost cost = mCosts.get(i);
            costHolder.bind(cost);
            costHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mPosition = costHolder.getAdapterPosition();
                    return false;
                }
            });

        }

        @Override
        public int getItemCount() {
            return mCosts.size();
        }

        public int getPosition() {
            return mPosition;
        }

        public void setCosts(List<Cost> costs) {
            mCosts = costs;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_SEARCH) {
            Date date = (Date) data.getSerializableExtra(SearchFragment.EXTRA_SEARCH_DATE);
            int conditionCode = data.getIntExtra(SearchFragment.EXTRA_SEARCH_CONDITION, CostLab.CONDITION_BY_ALL);
            updateUI(date, conditionCode);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_cost_list,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.new_cost:
                Cost cost = new Cost(UUID.randomUUID());
                CostLab.get(getActivity()).addCost(cost);
                Intent intent = CostActivity.newIntent(getActivity(), cost.getId());
                startActivity(intent);
                return true; //返回值为bool true表示任务已完成
            case R.id.search_button:
                FragmentManager manager = getFragmentManager();
                SearchFragment dialog = SearchFragment.newInstance();
                dialog.setTargetFragment(CostListFragment.this, REQUEST_SEARCH);
                dialog.show(manager, DIALOG_SEARCH);

            default:
                return super.onOptionsItemSelected(item);

        }
    }
}
